package com.cql.service.business.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cql.common.constant.FoodCircleConstant;
import com.cql.common.core.DO.CommentDo;
import com.cql.common.core.DO.MomentDO;
import com.cql.common.core.DO.UserDO;
import com.cql.common.core.DTO.CommentDTO;
import com.cql.common.core.DTO.CommentParamDTO;
import com.cql.common.exception.auth.PermissionDeniedException;
import com.cql.common.exception.moment.MomentNotExistException;
import com.cql.common.exception.user.UserNotExistException;
import com.cql.common.utils.StringUtils;
import com.cql.mapper.CommentMapper;
import com.cql.mapper.UserMapper;
import com.cql.service.business.AuthService;
import com.cql.service.business.CommentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author cql
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDo> implements CommentService {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());


    @Autowired
    private AuthService authService;

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<CommentDTO> listCommentOfMoment(Long userId, MomentDO momentDO) {
        /**
         * 需做数据校验
         */
        if (StringUtils.isNull(momentDO)) {
            logger.info("文章不存在");
            throw new MomentNotExistException();
        }

        // 数据权限校验
        boolean auth = authService.authMoment(momentDO, userId);

        if (!auth) {
            logger.info("游客或用户没有权限查看文章 {} ", momentDO.getTitle());
            throw new PermissionDeniedException();
        }

        List<CommentDTO> result = new ArrayList<>();

        /**
         * 查询数据,先获取复合条件的parent
         */
        QueryWrapper<CommentDo> wrapperParent = new QueryWrapper<>();
        wrapperParent.eq("type_id", momentDO.getMomentId());
        wrapperParent.eq("type", FoodCircleConstant.TYPE_MOMENT);
        wrapperParent.eq("level", 1);
        wrapperParent.orderByDesc("create_time");

        List<CommentDo> commentParent = commentMapper.selectList(wrapperParent);


        if (StringUtils.isNotNull(commentParent) && commentParent.size() > 0) {
            /**
             * 封装信息
             */
            for (CommentDo commentDo : commentParent) {
                CommentDTO m = new CommentDTO();
                //封装父级信息
                BeanUtils.copyProperties(commentDo, m);
                m.setFromUser(userMapper.selectById(commentDo.getFromUser()));
                m.setToUser(userMapper.selectById(commentDo.getToUser()));

                //获取子级数据并封装
                QueryWrapper<CommentDo> wrapperChild = new QueryWrapper<>();
                wrapperChild.eq("parent_id", commentDo.getCommentId());
                wrapperChild.eq("level", 2);
                List<CommentDo> commentChildren = commentMapper.selectList(wrapperChild);

                List<CommentDTO> child = new ArrayList<>();

                if (StringUtils.isNotNull(commentChildren) && commentChildren.size() > 0) {

                    for (CommentDo commentChild : commentChildren) {
                        CommentDTO c = new CommentDTO();
                        BeanUtils.copyProperties(commentChild, c);
                        c.setFromUser(userMapper.selectById(commentChild.getFromUser()));
                        c.setToUser(userMapper.selectById(commentChild.getToUser()));

                        child.add(c);
                    }
                }

                m.setChildren(child);


                result.add(m);
            }

        }

        return result;
    }

    @Override
    public CommentDTO insertComment(CommentParamDTO params) {
        CommentDTO result = new CommentDTO();
        if (StringUtils.isNotNull(params.getAccount()) && StringUtils.isNull(params.getToUser())) {
            QueryWrapper<UserDO> wrapper = new QueryWrapper<>();
            wrapper.eq("account", params.getAccount());
            wrapper.eq("status", 0);
            UserDO toUser = userMapper.selectOne(wrapper);

            if (StringUtils.isNull(toUser)) {
                logger.info("用户不存在:{}", params.getAccount());
                throw new UserNotExistException();
            }
            params.setToUser(toUser.getUserId());

            result.setToUser(toUser);
        }


        CommentDo comment = new CommentDo();
        BeanUtils.copyProperties(params, comment);

        commentMapper.insert(comment);

        /**
         * 再查询出来返回给前端
         */


        CommentDo commentDo = commentMapper.selectById(comment.getCommentId());

        BeanUtils.copyProperties(commentDo, result);
        result.setFromUser(userMapper.selectById(commentDo.getFromUser()));
        if (StringUtils.isNull(result.getToUser())) {
            result.setToUser(userMapper.selectById(commentDo.getToUser()));
        }


        //设置空的
        result.setChildren(new ArrayList<>());

        return result;
    }
}
